package com.market.category.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.market.category.dao.CategoryDao;
import com.market.category.domain.CategoryCommand;
import com.market.category.validator.CategoryValidator;

@Controller
public class CateUpdateController {
	@Autowired
	private CategoryDao categoryDao;

	@RequestMapping("/categoryShowToggle.do")
	public String toggle(@RequestParam("c_code") int c_code,
			@RequestParam("pageNum") int pageNum,
			@RequestParam("searchMarket") String keyWord){
		
		CategoryCommand categoryCommand = categoryDao.select(c_code);		
		
		if(categoryCommand.getShow().equals("y"))
			categoryCommand.setShow("n");
		else
			categoryCommand.setShow("y");
		
		categoryDao.update(categoryCommand);
		
		return "redirect:/categoryList.do?pageNum="+pageNum+"&searchMarket="+keyWord;
	}
	
	@RequestMapping(value="/categoryUpdate.do",method=RequestMethod.GET)
	public ModelAndView form(@RequestParam("c_code") int c_code,
			@RequestParam("pageNum") int pageNum,
			@RequestParam("searchMarket") String keyWord){
		
		CategoryCommand categoryCommand = categoryDao.select(c_code);
		
		ModelAndView mav = new ModelAndView();
		mav.setViewName("categoryUpdate");
		mav.addObject("command", categoryCommand);
		mav.addObject("pageNum", pageNum);
		mav.addObject("searchMarket", keyWord);
		
		return mav;
	}
	
	@RequestMapping(value="/categoryUpdate.do",method=RequestMethod.POST)
	public String submit(@ModelAttribute("command")CategoryCommand categoryCommand,
			BindingResult result,
			@RequestParam("pageNum") int pageNum,
			@RequestParam("searchMarket") String keyWord){
		
		new CategoryValidator().validate(categoryCommand, result);

		if(result.hasErrors()){
			return "categoryUpdate";
		}		
		categoryDao.update(categoryCommand);
		
		return "redirect:/categoryList.do?pageNum="+pageNum+"&searchMarket="+keyWord;
	}
}
